package com.qk.management.service.impl;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qk.common.PageResult;
import com.qk.domain.business.BusinessDO;
import com.qk.dto.business.BusinessDTO;
import com.qk.dto.business.BusinessListDTO;
import com.qk.entity.Business;
import com.qk.entity.BusinessTrackRecord;
import com.qk.entity.User;
import com.qk.management.mapper.BusinessMapper;
import com.qk.management.mapper.BusinessTrackRecordMapper;
import com.qk.management.mapper.UserMapper;
import com.qk.management.service.BusinessService;
import com.qk.vo.business.BusinessVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class BusinessServiceImpl extends ServiceImpl<BusinessMapper, Business> implements BusinessService {


    @Autowired
    private UserMapper userMapper;

    @Autowired
    private BusinessTrackRecordMapper businessTrackRecordMapper;

    @Override
    public void addBusiness(BusinessDTO businessdto) {
        Business business = BeanUtil.copyProperties(businessdto, Business.class);
        business.setUpdateTime(LocalDateTime.now());
        business.setCreateTime(LocalDateTime.now());
        this.baseMapper.insert(business);
    }

    @Override
    public PageResult<BusinessDO> listBusiness(BusinessListDTO dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        List<BusinessDO> list = this.baseMapper.listBusiness(dto);
        Page<BusinessDO> page = (Page<BusinessDO>) list;
        return PageResult.<BusinessDO>builder()
                .total(Long.valueOf(page.getTotal()).intValue())
                .rows(page.getResult())
                .build();

    }

    @Override
    public BusinessVO getBusinessInfoById(Integer id) {
        Business business = this.baseMapper.selectById(id);
        Integer userId = business.getUserId();
        User user = userMapper.selectById(userId);
        List<BusinessTrackRecord> businessTrackRecords = businessTrackRecordMapper.selectList(Wrappers.lambdaQuery(BusinessTrackRecord.class)
                .in(BusinessTrackRecord::getBusinessId, id)
        );
        BusinessVO businessVO = BeanUtil.copyProperties(business, BusinessVO.class);
        List<BusinessVO.BusinessTrackRecordVO> list = businessTrackRecords.stream().map(item -> {
            BusinessVO.BusinessTrackRecordVO vo = BeanUtil.copyProperties(item, BusinessVO.BusinessTrackRecordVO.class);
            vo.setAssignName(user.getName());
            return vo;
        }).toList();
        businessVO.setTrackRecords( list);
        return businessVO;

    }
}
